package com.finance.system.support.bean;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.finance.system.user.entity.UserEntity;
import com.finance.system.user.entity.UserOutbound;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Data
@Accessors(chain = true)
public class OffsetResult<T> extends Page<T> {

    public static <M> OffsetResult build(IPage page,Class<M> clazz){
        OffsetResult offsetResult = new OffsetResult();
        offsetResult.setCurrent(page.getCurrent())
                .setSize(page.getSize())
                .setTotal(page.getTotal())
                .setRecords(transferTo(page.getRecords(),clazz))
                .setOrders(page.orders());
        return offsetResult;

    }

    public static <M> OffsetResult build(IPage page){
        OffsetResult offsetResult = new OffsetResult();
        offsetResult.setCurrent(page.getCurrent())
                .setSize(page.getSize())
                .setTotal(page.getTotal())
                .setRecords(page.getRecords())
                .setOrders(page.orders());
        return offsetResult;

    }

    public static <M> OffsetResult changeRecords(IPage page,List<M> records){
        OffsetResult offsetResult = new OffsetResult();
        offsetResult.setCurrent(page.getCurrent())
                .setSize(page.getSize())
                .setTotal(page.getTotal())
                .setRecords(records)
                .setOrders(page.orders());
        return offsetResult;

    }

    private static <M> List<M> transferTo(List records, Class<M> clazz) {
        if(CollectionUtils.isEmpty(records) || clazz == null){
            return records;
        }
        ArrayList<M> list = new ArrayList<>();
        for (Object record : records) {
            try {
                M m = clazz.newInstance();
                BeanUtils.copyProperties(record,m);
                list.add(m);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<UserEntity> test = Arrays.asList(new UserEntity());
        List list = OffsetResult.transferTo(test, UserOutbound.class);
        System.out.println(list);
    }
}
